<?php

namespace App\Http\Controllers\Admin\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Permission;
use App\Models\Menu;
use App\Models\RoleHasMenuPermission;

use App\Traits\ApiResponse;
use Illuminate\Support\Facades\Route;

class PermissionController extends Controller
{

    use ApiResponse;

    /**
     * 权限列表
     * @Author wuyan（466720682@qq.com）
     * @return [Array]
     */
    public function lists()
    {
        $roles = Permission::query()->paginate(20);
        return $this->responseSucceed([
            'data' => $roles->items(),
            'total' => $roles->total(),
            'success' => true
        ]);
    }

    /**
     * 创建权限
     * @Author wuyan（466720682@qq.com）
     * @param Request
     * @return [Boolean]
     */
    public function create(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string',
            'action' => 'required|string',
            'menu_id' => 'required|integer',
        ]);
        Permission::query()->create($data);
        return $this->responseSucceed();
    }

    /**
     * 更新权限
     * @Author wuyan（466720682@qq.com）
     * @param Request
     * @return [Boolean]
     */
    public function update($id, Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string',
            'action' => 'required|string',
            'menu_id' => 'required|integer',
        ]);
        Permission::where('id', $id)->update($data);
        return $this->responseSucceed();
    }

    /**
     * 删除权限
     * @Author wuyan（466720682@qq.com）
     * @param Request
     * @return [Boolean]
     */
    public function delete($id)
    {
        Permission::where('id', $id)->delete();
        RoleHasMenuPermission::where('id', $id)->where('type', 1)->delete();
        return $this->responseSucceed();
    }

    /**
     * 一件生成所有路由权限
     * @Author wuyan（466720682@qq.com）
     * @return [Boolean]
     */
    public function generateAllPermission()
    {
        $actions = (new Permission())->generateAllPermission();
        if ( empty($actions) )
            return $this->responseFailed('未找到权限路由');
        else
            return $this->responseSucceed();
    }

}
